import cv2
import numpy as np

img = cv2.imread('../asset/dog.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

kernel = np.ones((3, 3), np.int8)
open1 = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
beijing = cv2.dilate(open1, kernel, iterations=1)
tmp = cv2.distanceTransform(open1, cv2.DIST_L2, 5)
ret, qianjing = cv2.threshold(tmp, 0.1*tmp.max(), 255, cv2.THRESH_BINARY)

beijing = np.uint8(beijing)
qianjing = np.uint8(qianjing)
unknow = cv2.subtract(beijing, qianjing)

ret, masker = cv2.connectedComponents(qianjing)
masker = masker +1
masker[unknow == 255] = 0
result = cv2.watershed(img, masker)
img[result == -1] = [0,0, 255]

while True:
    cv2.imshow('result', img)
    key = cv2.waitKey(10)
    if key & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()
